package zheezes.demo.lang;

public class Clone {
	public static void main(String[] args) {
		Parent parent = new Parent();
		System.out.println(parent);
		System.out.println(parent.clone());
		Child child1 = new Child();
		child1.name = "child1.name";
		child1.addr = "child1.addr";
		child1.gf = "child1.gf";
		Child child2 = child1.clone();
		System.out.println(child2.name);
		System.out.println(child2.addr);
		System.out.println(child2.gf);
	}
}

class Parent implements Cloneable {
	public String name = "parent";
	public String addr = "addr";
	
	public Parent() {
		System.out.println("new parent");
	}

	@Override
	public Parent clone() {
		System.out.println("clone parent");
		/*
		 * this is most important 
		 * copy the whole current object
		 * when subclass call, copy the subclass, but not the parent
		 */
		try {
			return (Parent) super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		/*
		 * when you just clone the current class, it's ok
		 * and the clone may be can't be inherited
		 * because any subclass can clone the parent's data
		 */
		return new Parent();
	}
}

class Child extends Parent {
	public String name = "child";
	public String gf = "gf";
	
	public Child() {
		System.out.println("new child");
	}

	@Override
	public Child clone() {
		Child newobj = (Child) super.clone();
		System.out.println("clone child");
		System.out.println(String.format("in child clone, name: %s, %s", name, newobj.name));
		newobj.name = "clone: " + name;
		return newobj;
	}
}
